package com.kaifamiao.controller;

import com.kaifamiao.pojo.Log;
import com.kaifamiao.pojo.User;
import com.kaifamiao.service.ILogService;
import com.kaifamiao.service.IUserService;
import com.kaifamiao.util.MDigest5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService iUserService = null;
    @Autowired
    ILogService iLogService = null;
    Logger logger = LoggerFactory.getLogger(getClass());
    //转向注册界面
    @RequestMapping("/signup")
    public String signUp(){
      return "user/signup";
    }
    //转向登录界面
    @RequestMapping("/signin")
    public String signIn(){
        return "user/signin";
    }
    //根据id得到一个患者实体
    public User getUser(int phoneNumber){
       return iUserService.findById(phoneNumber);
    }
    //根据手机号判断是否注册
    @RequestMapping("/isregister/{phoneNumber}")
    public @ResponseBody Boolean isRegister(@PathVariable String phoneNumber){
       User user =  iUserService.findByPhoneNumber(phoneNumber);
//       System.out.println(user);
       boolean flag = true;
       if(user!=null){
           flag=false;
       }
       return flag;
    }
    //注册患者
    @RequestMapping("/adduser")
    public String addUser(Model model, @Validated User user, BindingResult br) {
        if(br.hasErrors()){
            List<FieldError> errors = br.getFieldErrors();
            for (FieldError error : errors) {
                model.addAttribute(error.getField()+"err",error.getDefaultMessage());
            }
            return "/user/signup";
        }
        if(!user.getUserPass().equals(user.getReUserPass())){
            model.addAttribute("reUserPasserr","两次输入密码不一致 ");
            return "/user/signup";
        }
        user.setUserPass(MDigest5.getMD5(user.getUserPass()));
        iUserService.addUser(user);
        return "user/signin";
    }
    //登录
    @RequestMapping("/login.do")
    public String login(Model model, String phoneNumber, String userPass, HttpServletRequest request, HttpSession session){
        //存储日志
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = sdf.format(d);
        logger.info("用户登录"+"  登录时间:"+nowDate+"  手机号:"+phoneNumber+"  ip地址:"+getIpAddr(request));
        Log log = new Log();
        log.setLogPhoneNumber(phoneNumber);
        log.setLogIp(getIpAddr(request));
        log.setLogTime(nowDate);

        model.addAttribute("phoneNumber",phoneNumber);
        User user = iUserService.findByPhoneNumber(phoneNumber);
        if(user!=null){
            if(user.getUserPass().equals(MDigest5.getMD5(userPass))){
                session.setAttribute("user",user);
                log.setLogStatus("登录成功");
                logger.info("登录状态：登录成功");
                iLogService.AddLog(log);
                return "Patientinfohtml/index";
            }else{
                model.addAttribute("userPasserr","密码错误");
                log.setLogStatus("登录失败，密码错误");
                logger.info("登录状态：登录失败，密码错误");
                iLogService.AddLog(log);
                return "user/signin";
            }
        }else{
            model.addAttribute("phoneNumbererr","该手机号未注册");
            log.setLogStatus("登录失败，手机号未注册");
            logger.info("登录状态：登录失败，手机号未注册");
            iLogService.AddLog(log);
            return "user/signin";
        }
    }
    //获取用户ip地址
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
